問題描述
我應該使用什麼‑String 或 StringBuilder 將 SQL 查詢存儲在使用許多不同 SQL 查詢的代碼中 (what should i use‑String or StringBuilder for storing SQL queries in a code which uses many different SQL queries)
我有一個使用多個 SQL 查詢的代碼。我應該使用 String 來存儲這些不同的 SQL 查詢還是應該使用 StringBuilder。
如果使用 StringBuilder,我應該將每個查詢放在一個新的 StringBuilder 對像中還是使用單個 StringBuilder 對象。
參考解法
方法 1:
String is Immutable and StringBuilder is Mutable i.e. no new object is created when you edit StringBuilder unlike String.
If your application is used in large scale then its advisable to use StringBuilder instead of String
NOTE:‑ String is Thread Safe while StringBuilder is not
方法 2:
Well, if you are willing concatenate theses queries into one query part by part, then use unique StringBuilder object instead of concatenating String objects to each other. That's the best practise in terms of performance.
Avoid using unique StringBuilder for all (different) concatenation sets in your class, that thing must be dangerous if you're using threads. You have to define new StringBuilder object for each set of concatenated strings.